from tkinter import *
from tkinter import filedialog, messagebox
from settingHelper import setting
from projectHelper import project, Project
import os
import pickle
import utils


def newProject(*args):
    if utils.modified:
        select = messagebox.askyesnocancel("新建项目", "是否保存当前项目")
        if select is None or (select and not saveProject()):
            return
    project.load(Project())
    setattr(project, "fileName", None)
    utils.updateTitle()


def openProject(*args):
    path: str = filedialog.askopenfilename(
        title="打开项目",
        defaultextension=".lnp",
        filetypes=[("工程文件", ".lnp"), ("所有文件", "*")],
        initialdir=(
            os.path.expanduser("~\\Documents")
            if setting.last_directory is None
            else setting.last_directory
        ),
    )
    if not len(path):
        return
    setting.last_directory = os.path.dirname(path)
    with open(path, "rb") as f:
        loadProject: Project = pickle.load(f)
        project.load(loadProject)
    utils.updateTitle()


def saveProject(*args) -> bool:
    if not project.fileName is None:
        with open(project.fileName, "wb") as f:
            pickle.dump(project, f, pickle.HIGHEST_PROTOCOL)
        utils.setModified(False)
    elif not saveProjectAs():
        return False
    return True


def saveProjectAs(*args) -> bool:
    path: str = filedialog.asksaveasfilename(
        title="保存项目",
        defaultextension=".lnp",
        filetypes=[("工程文件", ".lnp"), ("所有文件", "*")],
        initialdir=(
            os.path.expanduser("~\\Documents")
            if setting.last_directory is None
            else setting.last_directory
        ),
        initialfile=project.projectName + ".lnp",
    )
    if not len(path):
        return False
    setting.last_directory = os.path.dirname(path)
    project.fileName = path
    project.projectName, _ = os.path.splitext(os.path.basename(path))
    utils.updateTitle()
    saveProject()
    return True


def importFiles():
    pass


def openConfigWindow():
    pass


def createMenu(root: Tk) -> None:
    menuBar: Menu = Menu(root)

    fileMenu = Menu(menuBar, tearoff=False)
    fileMenu.add_command(label="新建项目", command=newProject, accelerator="Ctrl + N")
    fileMenu.add_command(label="打开项目", command=openProject, accelerator="Ctrl + O")
    fileMenu.add_command(label="保存项目", command=saveProject, accelerator="Ctrl + S")
    fileMenu.add_command(
        label="另存为…",
        command=saveProjectAs,
        accelerator="Ctrl + Shift + S",
    )
    fileMenu.add_separator()
    fileMenu.add_command(label="导入", command=importFiles)
    fileMenu.add_separator()
    fileMenu.add_command(label="首选项", command=openConfigWindow)
    menuBar.add_cascade(label="文件", menu=fileMenu)

    root.config(menu=menuBar)
